package com.hbzhit.common.exception;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.hbzhit.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * sentinel流控自定义返回
 *
 * @author DING
 * @version 1.0
 * @date 2021/8/19 17:12
 */
@Component
@Slf4j
public class SentinelExceptionHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        if (e instanceof FlowException) {
            log.warn("触发流控", e);
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("系统繁忙，请稍后再试≧ ﹏ ≦")));
        } else if (e instanceof DegradeException) {
            log.warn("触发熔断", e);
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("服务暂时不可用，请稍后再试≧ ﹏ ≦")));
        } else if (e instanceof ParamFlowException) {
            log.warn("触发热点", e);
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("当前资源访问人数过多，请稍后再试≧ ﹏ ≦")));
        } else if (e instanceof SystemBlockException) {
            log.warn("触发系统保护", e);
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("服务器有点累了，请稍后再试≧ ﹏ ≦")));
        } else if (e instanceof AuthorityException) {
            log.warn("触发黑名单", e);
            httpServletResponse.getWriter().write(JSON.toJSONString(R.error("服务器拒绝访问")));
        }
    }
}
